<template>
	<view class="my-shop-hd">
		<view class="user-info">
			<view class="topuserinfo">
				<view class="dis-play">
				<button
				        class="avatar-btn"
				        style="border-radius: 50%"
				        open-type="chooseAvatar"
				        @chooseavatar="onChooseavatar"
				      >
					  <image class="avatar" mode="aspectFill" :src="useravatar ? useravatar : '/static/img/img.png'"></image>
				      </button>
				</view>
				<view class="dis-play">
					<view class="username">
						{{uname}}
					</view>
					<view class="usermobile" v-if="umobile == null || umobile == ''">
						暂无手机号
					</view>
					<view class="usermobile" v-else>
						{{umobile}}
					</view>
				</view>
			</view>
			
			<!-- <uni-list :border="false">
				
				
				<uni-list-chat :avatar-circle="true" :title="uname == null ? '暂无' : uname"
				 avatar="/static/img/img.png" :note="umobile == null ? '暂无' : umobile"
				  v-if="useravatar == '' || useravatar == null"></uni-list-chat>
				  
				<uni-list-chat  :title="uname == null ? '暂无' : uname"
				 :avatar="useravatar" :note="umobile == null ? '暂无' : umobile" v-else></uni-list-chat>
				
			</uni-list> -->
		
			<!-- <navigator class="phone-edit" @click="gobindpone" v-if="useredite"><uni-icons type="compose" size="16"></uni-icons></navigator> -->
			
			<view url="" class="phone-edit" @click="goeidteinfo" v-if="useredite"><uni-icons type="compose" size="16"></uni-icons></view>
			<!-- <view class="city" v-if="parentData" @click="gomypage">
				<uni-icons type="location" size="14"></uni-icons> {{addressvalue}}
			</view> -->
			<!-- <button open-type="getPhoneNumber" class="getphoneBT" @getphonenumber="getPhoneNumber">
			      获取手机号
			    </button> -->
			<button open-type="getPhoneNumber" @getphonenumber="bindGetPhoneNumber" hover-class="none"
									class="getphoneBT" v-if="umobile == null || umobile == ''">获取手机号</button>
		</view>
		<view class="my-card weui-media-box_appmsg">
			<view class="my-card-icon">
				<uni-icons type="vip" size="30"></uni-icons>
			</view>
			<view class="my-card-info">
				<text>超级抵现卡</text>
				<!-- <text>兑换金额当钱花</text> -->
			</view>
			<!-- <view class="instructions" @click="gotoprivilege_statement">特权使用说明</view> -->
		</view>
		<!-- {{parentData}} -->
	</view>
</template>

<script>
	import {get_phone,get_phoneone,userbind_mobile,userreload,userset_head} from "@/api/apiinfo";
	import { config	} from '@/config/env.js'
	export default {
		props:{
			parentData:{
				type:Boolean,
				default:false
			},
			useredite:{
				type:Boolean,
				default:false
			},
			userusername:{
				type:String,
				default:'暂无'
			},
		},
		data() {
		    return {
		      pickerRange: [], // 存储省市区数据
		      selectedProvince: '请选择', // 当前选择的省份
		      selectedCity: '', // 当前选择的城市
			  
			  addressinfo: [],
			  storageAdd: [0,0],
			  addressvalue:'未定义位置',
			  postdata:{
			  	province:'',//省份
			  	city:'',//城市
			  	address:'',//店面详细地址
			  },
			  shopnumber:0,
			  usermobile:'暂无',
			  // userusername:'暂无',
			  usernickname:'',
			  useravatar:'',
			  uname:'',
			  umobile:'',
			  
			  infoForm : { avatar: "" },
			  phoneNumber:''
		    };
		  },
		  mounted() { ////////////////// uni组件样式重定义 
			  let query1 = uni.createSelectorQuery().in(this).select(".uni-list-chat__header")
			  console.log(query1)
			  Array.prototype.forEach.call(query1, function(headerImage){
			  		headerImage.style.borderRadius = "50%";
			  });
			  let query2 = uni.createSelectorQuery().in(this).select(".uni-list-chat__header-image")
			  Array.prototype.forEach.call(query2, function(headerImage){
			  		headerImage.style.margin = "0";
			  });
			  let query3 = uni.createSelectorQuery().in(this).select(".uni-list-chat__content-title")
			  Array.prototype.forEach.call(query3, function(headerImage){
			  		contentTitle.style.color = "#fff";
			  });
			  let query4 = uni.createSelectorQuery().in(this).select(".uni-list-chat__content-note")
			  Array.prototype.forEach.call(query4, function(headerImage){
			  		contentTitle.style.color = "#fff";
			  });
			  let query5 = uni.createSelectorQuery().in(this).select(".uni-list-item")
			  Array.prototype.forEach.call(query5, function(headerImage){
			  		listItem.style.backgroundColor = "transparent";
			  });
			  let query6 = uni.createSelectorQuery().in(this).select(".uni-forms-item__label")
			  Array.prototype.forEach.call(query6, function(headerImage){
			  		itemLabel.style.fontSize = "14px";
			  });
			
		  // var str = document.getElementsByClassName("uni-list-chat__header");
		  // Array.prototype.forEach.call(str, function(headerImage){
		  // 					headerImage.style.borderRadius = "50%";
		  // });
			 //  var str = document.getElementsByClassName("uni-list-chat__header-image");
			 //  Array.prototype.forEach.call(str, function(headerImage){
				// headerImage.style.margin = "0";
			 //  });
			 //  var str = document.getElementsByClassName("uni-list-chat__content-title");
			 //  Array.prototype.forEach.call(str, function(contentTitle){
				// contentTitle.style.color = "#fff";
			 //  });
			 //  var str = document.getElementsByClassName("uni-list-chat__content-note");
			 //  Array.prototype.forEach.call(str, function(contentNote){
				// contentNote.style.color = "#fff";
			 //  });
			  // var str = document.getElementsByClassName("uni-list-item");
			  // Array.prototype.forEach.call(str, function(listItem){
			  // 	listItem.style.backgroundColor = "transparent";
			  // });
			  // var str = document.getElementsByClassName("uni-forms-item__label");
			  // Array.prototype.forEach.call(str, function(itemLabel){
			  // 	itemLabel.style.fontSize = "14px";
			  // });
			  
			  // console.log('顶部组件用户名：'+localStorage.getItem('username'))
			  // console.log('顶部组件手机号：'+localStorage.getItem('mobile'))
			  // this.userusername = localStorage.getItem('username');
			  // this.usernickname = localStorage.getItem('nickname');
			  // this.useravatar = localStorage.getItem('avatar');
			  // this.usermobile = localStorage.getItem('mobile');
			  // this.shopnumber = localStorage.getItem('shopnumber');
			  
			  let provincearr = uni.getStorageSync('province');
			  let cityarr = uni.getStorageSync('city');
			  if(provincearr == 'null' || provincearr === null){
				  console.log("没有省市信息")
			  }else{
				  provincearr = JSON.parse(provincearr);
				  cityarr = JSON.parse(cityarr);
				  console.log(JSON.stringify(provincearr))
				  this.storageAdd[0] = provincearr.id;
				  this.storageAdd[1] = cityarr.id;
				  this.addressvalue = provincearr.name;
				  this.addressvalue += ' - '+cityarr.name;
			  }
			
		  	
		  },
		  
		methods: {
			 
			bindGetPhoneNumber(e) {
				var that = this;
				let wxcode = ''
				console.log(JSON.stringify(e))
				if (e.detail.errMsg != 'getPhoneNumber:fail user deny') {
					uni.login({
						provider: 'weixin',
						success: function (loginRes) {
							//	打印临时凭证
							console.log('weiin----code')
							console.log(loginRes.code)
							wxcode = loginRes.code
							let datas = {
								encryptedData: e.detail.encryptedData,
								iv: e.detail.iv,
								code: wxcode,
							}
							get_phoneone(datas).then((res) => {
								console.log("get_phoneone接口返回数据：")
								console.log(JSON.stringify(res));
								console.log(JSON.stringify(res.data));
								uni.showToast({
									title: '获取成功',
									icon: 'success'
								})
								that.umobile = res.data.phoneNumber;
								console.log(that.umobile)
								that.bindPhone()
								
							}).catch(err => {
								console.log(JSON.stringify(err))
								if(err.msg){
									uni.showModal({
										title: '提示',
										content: '获取手机号报错：'+err.msg,
										showCancel: false,
										success: function (res) {
											if (res.confirm) {
												// uni.switchTab({ //内部页面跳转方式 
												// 	url: '/pages/shop/shop'
												// })
											} 
										}
									});
								}						
							})
							
						}
					});						 
				} else {
					uni.showModal({
						title: '温馨提示',
						content: '您已拒绝授权，无法获取手机号！',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.$emit("getContract", {});
								uni.navigateBack();
								// uni.switchTab({
								// 	url: "/pages/home/index/index"
								// })
							}
						}
					});
					return;	
				}
			},
			// getPhoneNumber(e) {
			// 	let appid = 'wx3213bbf0999402a7';
			// 	let secret = ''
			// 	uni.request({
			// 		url: 'https://api.weixin.qq.com/cgi-bin/token',
			// 		method: 'GET',
			// 		data: {
			// 			appid,
			// 			secret,
			// 			grant_type: 'client_credential'
			// 		},
			// 		success: (res) => {
			// 			console.log('获取手机号accessToken信息：')
			// 			console.log(JSON.stringify(res))
			// 			let accessToken = res.data.access_token
			// 			uni.request({
			// 				url: `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${accessToken}`,
			// 				method: 'POST',
			// 				data: {
			// 					code: e.detail.code
			// 				},
			// 				success: (result) => {
			// 					console.log('获取手机号信息：')
			// 					console.log(JSON.stringify(result))
			// 					if(result.data.errcode === 0) {
			// 						this.phoneNumber = result.data.phone_info.phoneNumber
			// 						this.bindPhone()
			// 					}
			// 				},
			// 				fail() {
			// 					// uni.showToast({
			// 					// 	title: '获取失败,请重试',
			// 					// 	icon: 'error'
			// 					// })
			// 					uni.showModal({
			// 						title: '提示',
			// 						content: '获取失败,请重试;',
			// 						showCancel: false,
			// 						success: function (res) {
			// 							if (res.confirm) {
			// 								// uni.switchTab({ //内部页面跳转方式 
			// 								// 	url: '/pages/shop/shop'
			// 								// })
			// 							} 
			// 						}
			// 					});
			// 				}
			// 			})
			// 		},
			// 		fail() {
			// 			uni.showModal({
			// 				title: '提示',
			// 				content: '获取失败,请重试;'+err.msg,
			// 				showCancel: false,
			// 				success: function (res) {
			// 					if (res.confirm) {
			// 						// uni.switchTab({ //内部页面跳转方式 
			// 						// 	url: '/pages/shop/shop'
			// 						// })
			// 					} 
			// 				}
			// 			});
			// 		}
			// 	})
			// },
			bindPhone(){ //接口传入后台
				let datas = {
					// shop_id:this.shopid,
					// realname:this.realname,
					mobile:this.umobile
					// code:this.verificationCode
				}
				console.log('保存手机号')
				console.log(JSON.stringify(datas))
				userbind_mobile(datas).then((res) => {
					console.log("userbind_mobile接口返回数据：")
					console.log(JSON.stringify(res));
					if(res.code == 1000){
						uni.setStorageSync('mobile',this.umobile);
						
					}else{
						uni.showModal({
							title: '提示',
							content: res.message,
							showCancel: false,
							success: function (res) {
								if (res.confirm) {
									// uni.switchTab({ //内部页面跳转方式 
									// 	url: '/pages/shop/shop'
									// })
								} 
							}
						});
					}
					
				}).catch(err => {
					console.log(JSON.stringify(err))
					if(err.errMsg){
						uni.showModal({
							title: '提示',
							content: '记录手机号报错：'+err.errMsg,
							showCancel: false,
							success: function (res) {
								if (res.confirm) {
									// uni.switchTab({ //内部页面跳转方式 
									// 	url: '/pages/shop/shop'
									// })
								} 
							}
						});
					}
					
				})
			},
			onChooseavatar(e){
				console.log(JSON.stringify(e))
			  new Promise((resolve, reject) => {
			  // 获取图片信息（临时路径）
			    uni.getImageInfo({
			      src: e.detail.avatarUrl,
			      success: (res) => {
			        console.log("图片信息", res)
			        resolve(res);
			      },
			      fail: (err) => {
			        console.error("获取图片信息失败了", err)
			        reject(err);
			      },
			    });
			  })
			    .then((res) => {
			      return Promise.resolve({
			        tempFilePath: e.detail.avatarUrl,
			      });
			    })
			    .then((res) => {
				console.log(e.detail.avatarUrl)
					  // this.useravatar = e.detail.avatarUrl;
					  
					  // 上传头像到服务器
					  uni.uploadFile({
							url: 'https://api.simajunshi.com/api/index/uploadPic', // 上传图片的接口地址
							filePath: e.detail.avatarUrl,     //所要上传的图片地址
							name: 'file',   //所要上传的文件类型
							header: {
								accept: 'application/json'
							},
							success: (uploadFileRes) => {    //成功的回调函数
								console.log(uploadFileRes);
								let regdata = JSON.parse(uploadFileRes.data)
								console.log(regdata)
								this.setuserheadpic(regdata.data.img_url)
								// resolve(uploadFileRes)
							}
						});
				  
			    })
			    .catch((err) => {
			    	// 获取失败时使用store内默认头像
			    	// infoForm.avatar = userStore.userInfo.avatar
			    });
			},
			setuserheadpic(pic){//设置头像
				let datas = {avatar:pic}
				console.log(pic)
				userset_head(datas).then((res) => {
					console.log("setuserheadpic接口返回数据：")
					console.log(JSON.stringify(res));
					this.useravatar = pic;
				}).catch(err => {
					console.log(JSON.stringify(err))
					if(err.msg){
						uni.showModal({
							title: '提示',
							content: '头像设置报错：'+err.msg,
							showCancel: false,
							success: function (res) {
								if (res.confirm) {
									// uni.switchTab({ //内部页面跳转方式 
									// 	url: '/pages/shop/shop'
									// })
								} 
							}
						});
					}
					
				})
			},
			isNull(value) {
				console.log(value === null)
			  return value === null;
			},
			gotoprivilege_statement(){
				uni.navigateTo({
					url: '/pages/shop/privilege_statement'
				});
			},
			gobindpone(){
				uni.navigateTo({ 
					url: '/pages/shop/bind_phone?type=2'
				});
			},
			goeidteinfo(){
				uni.navigateTo({ 
					url: '/pages/mypage/editename'
				});
			},
			gomypage(){
				uni.switchTab({ 
					url: '/pages/mypage/index'
				});
			},
			reloadaddress(){
				let provincearr = uni.getStorageSync('province');
				let cityarr = uni.getStorageSync('city');
				if(provincearr != null && provincearr != ''){
					  provincearr = JSON.parse(provincearr);
					  console.log(JSON.stringify(provincearr));
					  cityarr = JSON.parse(cityarr);
					  if(provincearr){
						  this.storageAdd[0] = provincearr.id;
						  this.addressvalue = provincearr.name;
					  }else{
						  this.storageAdd[0] = 0;
					  }
					  if(cityarr){
						  this.storageAdd[1] = cityarr.id;
						  this.addressvalue += ' - '+cityarr.name;
					  }else{
						  this.storageAdd[1] = 0;
					  }
					  
					  
				}
			},
			getuserreload(){//重新加载当前登录的用户数据
				userreload().then((res) => {
					console.log("userreload接口返回数据：")
					console.log(JSON.stringify(res));
					console.log("头像图：",res.data.avatar)
					// this.userRedata = res.data
					let user_name = res.data.realname//localStorage.getItem('username')
					if(user_name == '' || user_name == null){
						user_name = res.data.nickname//localStorage.getItem('nickname')
					}
					this.uname = user_name;
					this.umobile = res.data.mobile
					this.useravatar = res.data.avatar
					uni.setStorageSync('userToken', res.data.token);
					uni.setStorageSync('userId', res.data.id);
					uni.setStorageSync('username', res.data.realname);
					uni.setStorageSync('nickname', res.data.nickname);
					uni.setStorageSync('avatar', res.data.avatar);
					uni.setStorageSync('openid', res.data.openid);
					uni.setStorageSync('mobile', res.data.mobile);
					uni.setStorageSync('province', JSON.stringify(res.data.province));
					uni.setStorageSync('city', JSON.stringify(res.data.city));
				}).catch(err => {
					console.log(JSON.stringify(err))
					if(err.msg){
						uni.showModal({
							title: '提示',
							content: '数据接口报错：'+err.msg,
							showCancel: false,
							success: function (res) {
								if (res.confirm) {
									// uni.switchTab({ //内部页面跳转方式 
									// 	url: '/pages/shop/shop'
									// })
								} 
							}
						});
					}
					
				})
			},
			

		}
	};
	
</script>

<style lang="scss">
	.uni-list-chat{
		padding: 20rpx 20rpx 0;
		background-color: transparent;
	}
	.uni-list{
		background-color: transparent;
	}
	.uni-list:after{
		background-color: transparent;
	}
	.dis-play{
		display: inline-block;
	}
	// .avatar-btn {
	// 	width: 50px;
	// 	height: 50px;
	// 	display: inline-block;
	//     padding: 0;
	//     border-radius: 50%;
	//   }
	.avatar-btn {
	        display: flex;
	        flex-direction: column;
	        justify-content: center;
	        align-items: center;
	        background: none;
	        color: inherit;
	        border: none;
	        padding: 0;
	        font: inherit;
	        cursor: pointer;
	        outline: inherit;
	 
	        .avatar {
	            height: 100rpx;
	            width: 100rpx;
	            border-radius: 60rpx;
	            // border: 1px solid #eee;
	        }
	    }
	 
	    .avatar-btn::after {
	        border: none;
	    }
	
	.u-avatar {
	  width: 50px;
	  height: 50px;
	  border-radius: 50%;
	}
	.topuserinfo{
		display: flex;
		flex-direction: row;
		flex: 1;
		padding: 10px 15px;
		position: relative;
		background: #fff;
		overflow: hidden;
		.username{
			margin-top: 10rpx;
			margin-bottom: 10rpx;
			margin-left: 20rpx;
			font-size: 32rpx;
		}
		.usermobile{
			margin-left: 20rpx;
			font-size: 24rpx;
			color: #b9b9b9;
		}
		
	}
	.my-shop-hd{
		height: 280rpx;
		background: url("/static/img/my_bg.png") no-repeat center bottom;
		background-size: 100%;
		position: relative;
		
		.my-card{
			padding: 30rpx 50rpx;
			color: #f5c481;
			position: relative;
			display: flex;
			align-items: center;
			font-size: 24rpx;
			.my-card-icon{
				margin-right: 20rpx;
				width: 10%;
			}
			.my-card-info{
				width: 65%;
				text{
					display: block;
				}
			}
			.instructions{
				width: 25%;
				text-align: right;
				color: #734000;
				border-color: #f5c481;
				background-color: #f5c481;
				border-radius: 30rpx;
				padding: 10rpx 20rpx ;
			}
			
		}
		
		.user-info{
			position: relative;
			background-color: #E71F2C;
			.phone-edit{
				position: absolute;
				right: 40rpx;
				color: #fff;
				text-align: center;
				
				top: 44rpx;
				width: 60rpx;
				height: 60rpx;
				line-height: 54rpx;
				border-radius: 60rpx;
				background-color: rgba(0, 0, 0, .2);
			}
			.city{
				position: absolute;
				right: 30rpx;
				top: 44rpx;
				font-size: 24rpx;
				line-height: 40rpx;
				color: rgba(255, 255, 255, .8);
				background-color: rgba(0, 0, 0, .2);
				border-radius: 40rpx;
				padding: 2rpx 16rpx;
			}
		}
	}
	.getphoneBT{
		font-size: 24rpx;
		position: absolute;
		right: 120rpx;
		color: #fff;
		text-align: center;
		top: 44rpx;
		width: 180rpx;
		height: 60rpx;
		line-height: 60rpx;
		border-radius: 60rpx;
		background-color: rgba(0, 0, 0, 1);
	}
</style>